﻿using System;
using System.Collections.Generic;
using System.Text;
using Org.EasyWeb.SysUtil;
using Org.EasyWeb.DataAccess;
using System.Data;
using Org.EasyWeb.Sys;
using Org.EasyWeb.Data;
using Org.EasyWeb.Provider;
using Org.EasyWeb.Exception;
using System.Collections.Specialized;
using Org.EasyWeb.ConfigXml;

namespace Org.EasyWeb.Data
{
    public class TreeHelper
    {
        // Fields
        public const string DEFAULT_OPER = "Tree";
        private WebUpdate2DataSet fHost;
        private ModuleXml2File fModule;
        private Tree2XmlTableResolver fTreeResolver;
        public const string MOVE_OPER = "Move";
        public const string SORT_OPER = "Sort";
        public const string SUB_TREE_OPER = "SubTree";

        // Methods
        public TreeHelper(WebUpdate2DataSet host, ModuleXml2File module)
        {
            this.fHost = host;
            this.fModule = module;
            IMainTableResolver resolver = host as IMainTableResolver;
            this.fTreeResolver = resolver.MainResolver as Tree2XmlTableResolver;
            host.FilledCustomTables += new FilledCustomEventHandler(this.host_FilledCustomTables);
            host.FillingUpdateTables += new FillingUpdateEventHandler(this.host_FillingUpdateTables);
            host.FilledUpdateTables += new FilledUpdateEventHandler(this.host_FilledUpdateTables);
        }

        private string AddInitData()
        {
            object obj2 = GlobalVariable.Request.QueryString["ID"];
            if ((obj2 == null) || !(obj2.ToString() != this.fTreeResolver.RootID))
            {
                return string.Empty;
            }
            IParamBuilder equalSQL = null;
            equalSQL = SQLParamBuilder.GetEqualSQL(this.fTreeResolver.TreeFields.ID, obj2.ToString());
            string str2 = DataSetUtil.ExecuteScalar(string.Format("SELECT {0} FROM {1} WHERE {2}", this.fTreeResolver.TreeFields.Layer, this.fTreeResolver.TableName, equalSQL.SQL), this.fHost.DbConnection, equalSQL.Params).ToString();
            int num = str2.Length / 3;
            int num2 = 0;
            string str3 = string.Empty;
            if (!this.fTreeResolver.IsParentID)
            {
                num2++;
            }
            if (num <= num2)
            {
                return string.Empty;
            }
            for (int i = num2; i < num; i++)
            {
                int length = i * 3;
                if (i > num2)
                {
                    str3 = str3 + " OR ";
                }
                str3 = str3 + string.Format("{0} LIKE '{1}'", this.fTreeResolver.TreeFields.Layer, str2.Substring(0, length).PadRight(length + 3, '_'));
            }
            if (!(str3 != string.Empty))
            {
                return str3;
            }
            if (!this.fTreeResolver.IsParentID)
            {
                str3 = str3 + string.Format(" OR {0} = '{1}'", this.fTreeResolver.TreeFields.ID, this.fTreeResolver.RootID);
            }
            return string.Format("({0})", str3);
        }

        private void AddIsParentInfo()
        {
            DataTable table = DataSetUtil.CreateDataTable("_TREE_PARENT_INFO", new string[] { "ROOT_ID", "IS_PARENT" });
            table.Rows.Add(new object[] { this.fTreeResolver.RootID, this.fTreeResolver.IsParentID ? 1 : 0 });
            this.fHost.Tables.Add(table);
        }

        private void ChangeChildLayer(string id, string layer, string isLeaf)
        {
            if (isLeaf == "0")
            {
                string str = this.fTreeResolver.TreeFields.Layer;
                string parentID = this.fTreeResolver.TreeFields.ParentID;
                this.fTreeResolver.SelectWithParam(parentID, id);
                DataRow[] rowArray = this.fTreeResolver.HostTable.Select(string.Format("{0} = {1}", parentID, id), str + " ASC");
                for (int i = 0; i < rowArray.Length; i++)
                {
                    string str3 = rowArray[i][str].ToString();
                    string str4 = str3.Substring(str3.Length - 3, 3);
                    rowArray[i][str] = string.Format("{0}{1}", layer, str4);
                    this.ChangeChildLayer(rowArray[i][this.fTreeResolver.KeyFields].ToString(), rowArray[i][str].ToString(), rowArray[i][this.fTreeResolver.TreeFields.IsLeaf].ToString());
                }
            }
        }

        public void CommittingData()
        {
            int count = this.fTreeResolver.HostTable.Rows.Count;
            for (int i = 0; i < count; i++)
            {
                DataRow row = this.fTreeResolver.HostTable.Rows[i];
                if (row.RowState == DataRowState.Added)
                {
                    TreeUtil.SetAddedRow(this.fTreeResolver, row, this.fTreeResolver.TreeFields);
                }
            }
        }

        public void Delete()
        {
            TreeUtil.DeleteTree(this.fTreeResolver, this.fTreeResolver.TreeFields, GlobalVariable.Request.QueryString["ID"]);
        }

        private void FillChildTree(NameValueCollection queryString)
        {
            object obj2 = GlobalVariable.Request.QueryString["PID"];
            bool flag = false;
            if (obj2 == null)
            {
                obj2 = GlobalVariable.Request.QueryString["ID"];
                flag = true;
                DataTable table = DataSetUtil.CreateDataTable("_TREE_NODE_PARENT_INFO", new string[] { "ROOT_INFO" });
                if (this.fTreeResolver.IsParentID)
                {
                    table.Rows.Add(new object[] { this.fTreeResolver.RootID });
                }
                else
                {
                    object obj3 = DataSetUtil.ExecuteScalar(string.Format("SELECT {0} from {1} where {2} = '{3}'", new object[] { this.fTreeResolver.TreeFields.ParentID, this.fTreeResolver.TableName, this.fTreeResolver.TreeFields.ID, this.fTreeResolver.RootID }), this.fHost.DbConnection);
                    table.Rows.Add(new object[] { obj3 });
                }
                this.fHost.Tables.Add(table);
            }
            QueryParamCondition condition = new QueryParamCondition();
            string sql = this.AddInitData();
            if (sql != string.Empty)
            {
                condition.AddSQL(sql);
            }
            else if (obj2 != null)
            {
                string parentID = this.fTreeResolver.TreeFields.ParentID;
                if (!this.fTreeResolver.IsParentID && flag)
                {
                    parentID = this.fTreeResolver.TreeFields.ID;
                }
                else
                {
                    parentID = this.fTreeResolver.TreeFields.ParentID;
                }
                IParamBuilder equalSQL = SQLParamBuilder.GetEqualSQL(parentID, obj2.ToString());
                condition.AddSQL(equalSQL);
            }
            if (this.fHost.FilterSQL != null)
            {
                condition.AddSQL(this.fHost.FilterSQL.ToString());
            }
            string str4 = string.Empty;
            if ((this.fHost.DefaultSortField >= 0) && (this.fHost.DefaultSortField < this.fTreeResolver.ModelXml.ConfigItems.Length))
            {
                string fieldName = this.fTreeResolver.ModelXml.ConfigItems[this.fHost.DefaultSortField].FieldName;
                str4 = " ORDER BY " + fieldName;
                if (this.fHost.DefaultOrder != string.Empty)
                {
                    str4 = str4 + " " + this.fHost.DefaultOrder;
                }
            }
            else
            {
                str4 = " ORDER BY " + this.fTreeResolver.TreeFields.Layer;
            }
            string str6 = string.Format("SELECT {0} AS ID,{1} AS PID,{2} AS NAME,{3} AS ISLEAF FROM {4} WHERE {5}{6}", new object[] { this.fTreeResolver.TreeFields.ID, this.fTreeResolver.TreeFields.ParentID, this.fTreeResolver.TreeFields.Name, this.fTreeResolver.TreeFields.IsLeaf, this.fTreeResolver.TableName, condition.SQL, str4 });
            this.fTreeResolver.SelectSql("_TREE", str6, condition.Params);
        }

        public string GetDataXslt(PageStyle style, string operation)
        {
            if ((style == PageStyle.Custom) && (operation == "Tree"))
            {
                return @"Tk2Template\TreeTrans.xslt";
            }
            return string.Empty;
        }

        public string GetDefaultPage(bool isPost, PageStyle style, string operation, PageX pageX, string retURL)
        {
            string str = (this.Module.DefaultPage == null) ? string.Empty : this.Module.DefaultPage.GetDefaultPage(this.fTreeResolver, isPost, style, pageX, this.Module.Key);
            if (str != string.Empty)
            {
                return str;
            }
            if (!isPost)
            {
                if (style == PageStyle.Update)
                {
                    return string.Format("../Pages/WebTreeXmlPage.{0}?Source={1}&ID={2}", pageX, this.Module.Key, GlobalVariable.Request["ID"]);
                }
            }
            else
            {
                switch (this.fHost.SaveMethod.ToLower())
                {
                    case "save":
                        {
                            if (this.fTreeResolver.KeyCount > 1)
                            {
                                throw new FrameException(string.Format("树型结构{0}不能有多个主键!", this.fTreeResolver.TableName));
                            }
                            object obj2 = this.fTreeResolver.HostTable.Rows[this.fTreeResolver.HostTable.Rows.Count - 1][this.fTreeResolver.KeyFields];
                            return string.Format("../Pages/WebTreeXmlPage.{1}?Source={0}&PID={2}", this.Module.Key, pageX.ToString(), obj2);
                        }
                    case "savenew":
                        {
                            string str3 = string.Empty;
                            if (style == PageStyle.Insert)
                            {
                                return GlobalVariable.Request.Url.ToString();
                            }
                            if (style == PageStyle.Update)
                            {
                                object obj3 = this.fTreeResolver.HostTable.Rows[0][this.fTreeResolver.TreeFields.ParentID];
                                return string.Format("../Pages/WebInsertXmlPage.{1}?Source={0}&PID={2}", this.Module.Key, pageX.ToString(), obj3);
                            }
                            return str3;
                        }
                }
            }
            return string.Format("../Pages/WebTreeXmlPage.{0}?Source={1}", pageX, this.Module.Key);
        }

        public string GetDefaultXsltTemplate(PageStyle style, string operation)
        {
            string defaultXsltTemplate = this.Module.GetDefaultXsltTemplate(style, operation);
            if (!(defaultXsltTemplate == string.Empty))
            {
                return defaultXsltTemplate;
            }
            if ((style == PageStyle.Custom) && (operation == "Tree"))
            {
                return @"..\Tk2Template\TreeTemplate.xslt";
            }
            if (style == PageStyle.Detail)
            {
                return @"..\Tk2Template\TreeDetailTemplate.xslt";
            }
            return string.Empty;
        }

        private int GetRowNum(DataTable table, string id)
        {
            for (int i = 0; i < table.Rows.Count; i++)
            {
                if (table.Rows[i][this.fTreeResolver.KeyFields].ToString() == id)
                {
                    return i;
                }
            }
            return -1;
        }

        public bool GetSupportDoubleTransform(PageStyle style, string operation)
        {
            return ((style != PageStyle.Custom) || (!(operation == "SubTree") && !(operation == "Move")));
        }

        public string GetXsltFile(bool isIe, PageStyle style, string operation)
        {
            if ((style == PageStyle.Custom) && (operation == "SubTree"))
            {
                return "../Tk2Template/TreeExpand.xslt";
            }
            return this.Module.GetXsltFile(style, operation);
        }

        private void host_FilledCustomTables(object sender, FilledCustomEventArgs e)
        {
            string operation = e.Operation;
            if (operation != null)
            {
                if (!(operation == "Tree"))
                {
                    if (!(operation == "SubTree"))
                    {
                        if (!(operation == "Move"))
                        {
                            if (operation == "Sort")
                            {
                                this.SortTree(e.QueryString);
                            }
                            return;
                        }
                        this.MoveTree(e.QueryString);
                        return;
                    }
                }
                else
                {
                    this.AddIsParentInfo();
                    return;
                }
                this.FillChildTree(e.QueryString);
            }
        }

        private void host_FilledUpdateTables(object sender, FilledUpdateEventArgs e)
        {
            if (e.Style == PageStyle.Detail)
            {
                object rootID;
                if (this.fTreeResolver.IsParentID)
                {
                    rootID = this.fTreeResolver.RootID;
                }
                else
                {
                    rootID = DataSetUtil.ExecuteScalar(string.Format("SELECT {0} from {1} where {2} = '{3}'", new object[] { this.fTreeResolver.TreeFields.ParentID, this.fTreeResolver.TableName, this.fTreeResolver.TreeFields.ID, this.fTreeResolver.RootID }), this.fHost.DbConnection);
                }
                DataTable table = DataSetUtil.CreateDataTable("_TREE_ROOT_INFO", new string[] { "ROOT_ID" });
                table.Rows.Add(new object[] { rootID });
                this.fHost.Tables.Add(table);
            }
        }

        private void host_FillingUpdateTables(object sender, FillingUpdateEventArgs e)
        {
            if (e.Style == PageStyle.Delete)
            {
                e.Handled[this.fTreeResolver] = true;
            }
        }

        private void MoveTree(NameValueCollection queryString)
        {
            TreeUtil.MoveTree(this.fTreeResolver, this.fTreeResolver.TreeFields, queryString["Oid"], queryString["Nid"]);
            this.fHost.Commit();
        }

        private void SortTree(NameValueCollection queryString)
        {
            string id = queryString["ID"].ToString();
            string str2 = queryString["Direct"].ToString();
            string str3 = DataSetUtil.ExecuteScalar(string.Format("SELECT {0} FROM {1} WHERE {2} = {3}", new object[] { this.fTreeResolver.TreeFields.Layer, this.fTreeResolver.TableName, this.fTreeResolver.KeyFields, id }), this.fHost.DbConnection).ToString();
            string str4 = str3.Substring(0, str3.Length - 3);
            this.fTreeResolver.SetCommands(AdapterCommand.Update);
            this.fTreeResolver.Select(string.Format("WHERE {0} LIKE '{1}___' ORDER BY {0}", this.fTreeResolver.TreeFields.Layer, str4));
            if ((this.fTreeResolver.HostTable != null) && (this.fTreeResolver.HostTable.Rows.Count != 0))
            {
                int rowNum = this.GetRowNum(this.fTreeResolver.HostTable, id);
                if (rowNum != -1)
                {
                    string str5 = str2.ToLower();
                    if (str5 != null)
                    {
                        if (!(str5 == "up"))
                        {
                            if (str5 == "down")
                            {
                                if (rowNum == (this.fTreeResolver.HostTable.Rows.Count - 1))
                                {
                                    return;
                                }
                                this.SwapLayer(rowNum, rowNum + 1);
                            }
                        }
                        else
                        {
                            if (rowNum == 0)
                            {
                                return;
                            }
                            this.SwapLayer(rowNum, rowNum - 1);
                        }
                    }
                    this.fHost.Commit();
                }
            }
        }

        private void SwapLayer(int rowNum1, int rowNum2)
        {
            string layer = this.fTreeResolver.TreeFields.Layer;
            string isLeaf = this.fTreeResolver.TreeFields.IsLeaf;
            DataRow row = this.fTreeResolver.HostTable.Rows[rowNum1];
            DataRow row2 = this.fTreeResolver.HostTable.Rows[rowNum2];
            string str3 = row[layer].ToString();
            row[layer] = row2[layer];
            row2[layer] = str3;
            this.ChangeChildLayer(row[this.fTreeResolver.KeyFields].ToString(), row[layer].ToString(), row[isLeaf].ToString());
            this.ChangeChildLayer(row2[this.fTreeResolver.KeyFields].ToString(), row2[layer].ToString(), row2[isLeaf].ToString());
        }

        // Properties
        public ModuleXml2File Module
        {
            get
            {
                return this.fModule;
            }
        }

    }
}
